/*
 * CS_PVP_ROOM_CREATE.cpp
 *
 *  Created on: 2014. 1. 3.
 *      Author: mega
 */

#include "../../User.h"
#include "../../Command.h"
#include "../../NLogic/Space.h"
#include "../../NLogic/Party.h"
#include "../../NLogic/Static.h"

namespace ProjectZ { namespace NCommand {

void SendFailPVPRoomCreate(User * pUser, int ack)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ack);
	pAck->MakePacket(CMD_SC_PVP_ROOM_CREATE);
	pUser->Send(pAck);
}

void Command::CS_PVP_ROOM_CREATE(User * pUser, ::Network::Packet * pPacket)
{
/*	CS_PVP_CREATE_ROOM			0x1321
	{
	}

	SC_PVP_CREATE_ROOM			0x1322
	{
		s16 ack;
		u32	room_number;
	}*/

	PREPARE_PACKET;

	NLogic::Space * pWorld = pUser->GetSpace();
	if (NULL == pWorld)
	{
		DEBUGLOG("%s : pWorld is NULL!", __FUNCTION__);
		SendFailPVPRoomCreate(pUser, ACK_NO_SPACE);
		return;
	}

	if (pWorld->GetData()._spaceType != NLogic::Space::SpaceType::WORLD)
	{
		DEBUGLOG("%s : User Space is Not WORLD!", __FUNCTION__);
		SendFailPVPRoomCreate(pUser, ACK_NO_SPACE);
		return;
	}

	if (pUser->GetEnumState() != User::EnumState::__NONE__)
	{
		DEBUGLOG("%s : User Status is Not Normal!!", __FUNCTION__);
		SendFailPVPRoomCreate(pUser, ACK_UNKNOWN_ERROR);
		return;
	}


	NLogic::Static::SPACEVECTOR & clsPVPRoomVector = NLogic::Static::InstancePtr()->GETPVPROOMVECTOR();

	int roomCount = static_cast<int>(clsPVPRoomVector.size());

	if (roomCount >= MAX_NEW_PVP_ROOM)
	{
		DEBUGLOG("%s : PVP Room MAX!!", __FUNCTION__);
		SendFailPVPRoomCreate(pUser, ACK_PVP_PK_OVER_ROOM_COUNT);
		return;
	}

	NLogic::IndexerPVP * pPVPIndex = NLogic::Static::InstancePtr()->GETPVPINDEXPOOL()->NEW();
	if (NULL == pPVPIndex)
	{
		DEBUGLOG("%s : pPVPIndex is NULL!!", __FUNCTION__);
		SendFailPVPRoomCreate(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	// Party 생성
	NLogic::Party * pPVPRoomParty = NLogic::Static::Instance().GETPARTYPOOL()->NEW();
	pPVPRoomParty->Open(pUser);

	// PVP Space생성
	NLogic::Space::Data clsData;
	clsData._maxUser	= 2;
	clsData._spaceType	= NLogic::Space::SpaceType::NEW_PVP_ROOM;

	NLogic::Space * pPVPRoomSpace = NLogic::Static::Instance().GETSPACEPOOL()->NEW();
	pPVPRoomSpace->Open(pUser, clsData);
	pPVPRoomSpace->SetParty(pPVPRoomParty);
	pPVPRoomSpace->SetPVPIndexer(pPVPIndex);

	// 방장 입장
	pWorld->LeaveUser(pUser);
	pPVPRoomSpace->EnterUser(pUser);

	pUser->SetEnumState(User::EnumState::NEW_PVP_ROOM_WAIT);

	// 방 설정
	clsPVPRoomVector.push_back(pPVPRoomSpace);

	// 응답
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	*pAck << static_cast<uint32_t>(pPVPIndex->GetIndex());
	pAck->MakePacket(CMD_SC_PVP_ROOM_CREATE);
	pUser->Send(pAck);

	// 60초 타이머 가동
	pPVPRoomParty->SetState(NLogic::Party::State::NEW_PVP_ROOM_ACCEPT_WAIT);
}

} /*NCommand*/ } /*ProjectZ*/
